package com.rech.xbexpress3;

import com.rech.dialog.CustomDialog;
import com.rech.scannergun.ScannerGunManager;
import com.rech.utils.OtherUtil;
import com.rech.xbexpress3.R;
import com.sjl.idcard.IdentityCardHandler;
import com.sjl.idcard.entity.IdentityCard;
import com.sjl.idcard.listener.CompoundListener;
import com.sjl.idcard.util.BitmapUtils;
import com.sjl.idcard.util.ByteUtils;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Bitmap;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Kd5Activity extends AppCompatActivity {
    private static final String TAG = "Kd5Activity";
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;
    ImageView iv_front;
    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;

    private long kd5_clicktime = 0;
    String kd_cabinetgridid;
    public static final long TIME_INTERVAL = 3000L;
    private String m_cardid = "";
    private String m_name = "";
    private final Handler mHideHandler = new Handler();
    //private EditText ydh;
    //ScannerGunManager scannerGunManager;
    private CustomDialog commitDialog;
    EditText editText;
    EditText edit_ydh;
    private Timer countTimer;
    private TextView djs;
    private int jjcount = 100;

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setContentView(R.layout.activity_kd5);
        djs = findViewById(R.id.tv_djs);
        mVisible = true;getSupportActionBar().hide();

        //ydh = (EditText)findViewById(R.id.kd5_ydh);
        String id =  sharedPreferences.getString("kd_lj_id", "");
        m_name = sharedPreferences.getString("kd_lj_name", "");
        String phone =  sharedPreferences.getString("kd_lj_phone", "");
        String toname = sharedPreferences.getString("kd_lj_toname", "");
        m_cardid =  sharedPreferences.getString("kd_lj_cardid", "");
        final String exp_type = sharedPreferences.getString("kd_lj_exp_type", "");
        String packageid = sharedPreferences.getString("kd_lj_packageid", "");
        String gridnum = sharedPreferences.getString("kd_gridnum", "");
        //iv_front = findViewById(R.id.iv_front);

        //sp数据存储可能比较慢，改为intent传递
        m_name = getIntent().getStringExtra("kd_lj_name");
        m_cardid =  getIntent().getStringExtra("kd_lj_cardid");

        TextView iter = (TextView) findViewById(R.id.kd5_name);
        iter.setText(m_name);
        iter = (TextView) findViewById(R.id.kd5_sjh);
        iter.setText(phone);
        iter = (TextView) findViewById(R.id.kd5_sfz);
        iter.setText(m_cardid);
        iter = (TextView) findViewById(R.id.kd5_xdlx);
        if(exp_type.equals("0"))//0为柜子下单 2为菜鸟裹裹有揽件码
            iter.setText("微信下单");
        else
            iter.setText("菜鸟裹裹");
        iter = (TextView)findViewById(R.id.kd5_gridnum);
        iter.setText(gridnum);

        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phoneServe = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phoneServe);

        TextView jj4_qx = (TextView) findViewById(R.id.tv_back);
        jj4_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(4008, intent);
                Exit();
                finish();
            }
        });

        Button kd5_zfkg = (Button) findViewById(R.id.kd5_zfkg);
        kd5_zfkg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - kd5_clicktime > TIME_INTERVAL) {
                    kd5_clicktime = nowTime;
                    //String ydhstr = ydh.getText().toString();
                    /*if(ydhstr.length() < 6)
                    {
                        Toast.makeText(Kd5Activity.this, "运单号不能小于6位", Toast.LENGTH_SHORT).show();
                        return ;
                    }*/
                    SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                    String kd_lj_id  =  sharedPreferences.getString("kd_lj_id", "");

                    new FetchKDPayOrderTask(kd_lj_id,"").execute();
                    //showRegisterDialog();
                }

            }
        });

        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                //djs.setText(String.valueOf(OtherUtil.jjcount));
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    Intent intent = new Intent();
                    setResult(4008, intent);
                    Exit();
                    finish();
                }

            }
        },0,1000);

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);



        /*IdentityCard identityCard = getIDCardInfo();
        IdentityCardHandler identityCardHandler = IdentityCardHandler.getInstance(this);
        identityCardHandler.compound(identityCard, new CompoundListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(IdentityCard identityCard) {
                Bitmap frontBitmap = identityCard.getFrontBitmap();
                //Bitmap backBitmap = identityCard.getBackBitmap();
//                String frontImageBase64 = identityCard.getFrontImageBase64();
//                String backImageBase64 = identityCard.getBackImageBase64();
                iv_front.setImageBitmap(BitmapUtils.scaleBitmap(frontBitmap, 1.2f));



            }

            @Override
            public void onFailed(Throwable t) {
                Log.e(TAG, "身份证合成失败", t);
            }
        });*/

    }

    private void showRegisterDialog() {
        View view = View.inflate(this, R.layout.dialog_commit, null);
        initregisterDialogView(view);
        commitDialog = new CustomDialog(this, OtherUtil.dp2px(600), OtherUtil.dp2px(300),
                view, R.style.CustomDialog);
        commitDialog.show();

        /*scannerGunManager = new ScannerGunManager(new ScannerGunManager.OnScanListener() {
            @Override
            public void onResult(String code) {
                //Toast.makeText(Kd5Activity.this, "扫描枪：" + code, Toast.LENGTH_SHORT).show();
                edit_ydh.setText(code);
            }
        });*/
    }

    private void initregisterDialogView(View view) {
        //ImageView imgClose = view.findViewById(R.id.img_dialog_register_activity_close);
        Button btnConfirmDelete = view.findViewById(R.id.btn_dialog_register_activity_submit);
        editText = view.findViewById(R.id.et_fei);
        edit_ydh = view.findViewById(R.id.kd5_ydh);

        /*imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });*/

        btnConfirmDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (edit_ydh.getText().toString().trim().equals("")) {
                    Toast.makeText(Kd5Activity.this, "请回填运单号", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (editText.getText().toString().trim().equals("")) {
                    Toast.makeText(Kd5Activity.this, "请输入运费金额", Toast.LENGTH_SHORT).show();
                    return;
                }

                String ydhstr = edit_ydh.getText().toString().trim();
                SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                String kd_lj_id = sharedPreferences.getString("kd_lj_id", "");
                new FetchUpdateEXPorderTask(kd_lj_id, ydhstr, editText.getText().toString().trim()).execute();
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }

   /* @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (scannerGunManager.dispatchKeyEvent(event)) {
            return true;
        }

        return super.dispatchKeyEvent(event);
    }*/

    private void Exit(){
        EventBus.getDefault().unregister(this);
        //IdentityCardHandler.getInstance(this).release();
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }

    @SuppressLint("InlinedApi")
    private void show() {
        mVisible = true;


    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    private IdentityCard getIDCardInfo() {
        //正面
        String name = "宋某某";
        String sex = "男";
        String nation = "汉";
        String birthday = "20200501";
        String address = "福建省厦门市思明区前埔工业园56号";
        String idCardNo = "450981199210150412";
        Bitmap headImg = headImgToBitmap();
        //反面
        String police = "思明区公安局";
        String expiryDate = "2020050120200502";
        IdentityCard identityCard = new IdentityCard(m_name, sex, nation, birthday, address, m_cardid,
                police, expiryDate, headImg);
        return identityCard;
    }

    private Bitmap headImgToBitmap() {
//        InputStream inputStream = BitmapUtils.openAssets(this, "headdata.txt");
//        String content = readFile(inputStream);
//        byte[] bytes = ByteUtils.hexStringToByteArr(content);
//        Bitmap bitmap = BitmapUtils.byteArrToBitmap(bytes);


        Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.usercard)).getBitmap();
        return bitmap;
    }

    private String readFile(InputStream inputStream) {
        BufferedReader reader = null;
        String str;
        StringBuilder sb = new StringBuilder();
        try {
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputReader);
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }


   /* @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == 4101 && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(Constant.CODED_CONTENT);
                //result.setText("扫描结果为：" + content);

                ydh.setText(content);

            }
        }
    }*/

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10406:
                handleGetIO485Task(message.obj);
                break;
            case 10407:
                Toast.makeText(Kd5Activity.this, "获取柜子状态失败", Toast.LENGTH_SHORT).show();
                break;
            case 10422:
                handleLocalKdOpenGrid(message.obj);
                //handleKDPayOrder(message.obj);
                break;
            case 10423:
                Toast.makeText(Kd5Activity.this, "获取柜子状态失败", Toast.LENGTH_SHORT).show();
                break;
            case 10501:
                intent.putExtra("kd_lj_name", m_name);
                intent.putExtra("kd_lj_cardid", m_cardid);
                setResult(4012, intent);
                Exit();
                finish();
                break;
            case 20000:
                handleDJS();
                break;
        }
    }

    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }

    private void handleGetIO485Task(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();

                editor.putString("open",obj.toString());
                new FetchOpenLocalGridTaskv2ForKD(obj.toString()).execute();
                Intent intent = new Intent();
                intent.putExtra("kd_lj_name", m_name);
                intent.putExtra("kd_lj_cardid", m_cardid);
                setResult(4012, intent);
                Exit();
                finish();
            }
            if(result.getString("code").equals("300")){
                AlertDialog.Builder builder = new AlertDialog.Builder(Kd5Activity.this);
                View view = View
                        .inflate(Kd5Activity.this, R.layout.notic_dialog, null);
                ImageView iv = view.findViewById(R.id.tv_cycler);
                SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                String cnImage     =  sharedPreferences.getString("CabinetType_gzh","");
                new FetchUrlImageTask(cnImage,iv).execute();

                builder.setView(view);
                builder.setCancelable(true);
                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.setCanceledOnTouchOutside(true);

            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }
    public void handleLocalKdOpenGrid(Object obj){

    }
    public void handleKDPayOrder(Object obj) {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                kd_cabinetgridid = result.getJSONObject("data").getString("cabinetgridid");
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("kd5_msg",result.getString("msg"));
                editor.putString("kd5_cabinetgridid",kd_cabinetgridid);
                editor.apply();
                //                       /* Intent intent = new Intent();
//                        //intent.putExtra("sn", resultString);
//                        setResult(4012, intent);*/
//                View cv = getWindow().getDecorView();
//                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
//                adbuilder.setTitle(result.getString("msg"));
//                adbuilder.setMessage("2秒后自动关闭！");
//                adbuilder.setCancelable(true);
//                final AlertDialog dlg = adbuilder.create();
//                dlg.show();
//                final Timer t = new Timer();
//                t.schedule(new TimerTask() {
//                    public void run() {
//                       /* Intent intent = new Intent();
//                        //intent.putExtra("sn", resultString);
//                        setResult(4012, intent);*/
//                        dlg.dismiss();
//                        t.cancel();
//                        //finish();
//                    }
//                }, 2000);

            }

            if(result.getString("code").equals("200")){
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);

            }

        }catch(Exception e){
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }
}
